/*
 * @Description: gomall
 * @Author: ylf
 * @Date: 2025-03-04 17:26:33
 * @LastEditTime: 2025-03-04 17:31:08
 * @LastEditors: ylf
 * @FilePath: \ltool\encrypt\rsa.go
 */
package encrypt

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
	"strings"
)

const (
	privateBlockType = "RSA PRIVATE KEY"
	publicBlockType  = "RSA PUBLIC KEY"
	PEM_BEGIN        = "-----BEGIN RSA PRIVATE KEY-----\n"
	PEM_END          = "\n-----END RSA PRIVATE KEY-----"
)

func F私钥加上前后缀(privateKey string) string {
	if !strings.HasPrefix(privateKey, PEM_BEGIN) {
		privateKey = PEM_BEGIN + privateKey
	}
	if !strings.HasSuffix(privateKey, PEM_END) {
		privateKey = privateKey + PEM_END
	}
	return privateKey
}

func F解析rsa私钥(privateKey string) (*rsa.PrivateKey, error) {
	privateKey = F私钥加上前后缀(privateKey)
	// 2、解码私钥字节，生成加密对象
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("私钥信息错误！")
	}
	// 3、解析DER编码的私钥，生成私钥对象
	priKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {

		return nil, err
	}
	return priKey.(*rsa.PrivateKey), nil
}

func FRsa解密(tk, 私钥 string) (str string, err error) {
	priv, err := F解析rsa私钥(私钥)
	if err != nil {
		return
	}
	ciphertext, err := base64.StdEncoding.DecodeString(tk)
	if err != nil {
		return
	}
	//plaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, []byte(tk), nil)
	plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
	if err != nil {
		return
	}
	str = string(plaintext)
	return
}

func Rsa2签名(signContent string, privateKey string, hash crypto.Hash) string {
	shaNew := hash.New()
	shaNew.Write([]byte(signContent))
	hashed := shaNew.Sum(nil)
	priKey, err := F解析rsa私钥(privateKey)
	if err != nil {
		fmt.Println(err, 33333333333)
		return ""
	}

	signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed)
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString(signature)
}
